package net.jiupinshi.interceptor;

import com.alibaba.fastjson.JSON;
import net.jiupinshi.common.StaticProperty;
import net.jiupinshi.customAnnotation.LoginAnnotation;
import net.jiupinshi.common.Result;
import net.jiupinshi.enums.CommonEnum.ResultStatusEnum;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Despription: 登录拦截
 * @Author: penghui.guo
 * @Date: 2018/10/5 13:36
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

    private final Result needLoginResult = new Result(ResultStatusEnum.NOT_LOGIN.code, ResultStatusEnum.NOT_LOGIN.desc);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            LoginAnnotation loginAnnotation = handlerMethod.getMethodAnnotation(LoginAnnotation.class);
            if(loginAnnotation != null && request.getSession().getAttribute(StaticProperty.SESSION_KEY) == null){
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json; charset=utf-8");
                response.getWriter().print(JSON.toJSONString(needLoginResult));
                return false;
            }
        }
        return true;
    }
}
